Flag word

A flag word is a generic term for a word (value) used to indicate conditions within a binary computer. In particular, the byte can be used to show up to 8 discrete conditions. Essentially, each bit represents one flag, capable of showing two states.

A flag word can be seen as a bit array with a short, constant length.

Contents

Examples

Processor status register

Taking the example of a 6502 processor's status register, the following information was held within 8 bits:

As you can see, a lot of information about the state of the processor can be packed into 8 bits.

Unix process exit code

A more general example would be the use of a Unix exit status as a flag word. In this case, the exit code is by the programmer to pass status information to another process. An imaginary program which returns the status of 8 burglar alarm switches connected to the printer port could set each of the bits in the exit code in turn, depending on whether the switches are closed or open.

Extracting bits from flag words

To read a status byte, assuming your programming language does not offer this facility by default, is quite easy. You simply need to AND the status byte with a mask byte. The mask byte should have only the bit corresponding to the flag you want to read set, as in the example below.

Suppose that status byte 103 (decimal) is returned, and that we want to check flag bit 5.

The flag we want to read is number 5 (counting from zero) - so the mask byte will be 2^5 = 32. ANDing 32 with 103 gives 32, which means the flag bit is set. If the flag bit was not set, the result would have been 0.

In modern computing, the shift operator (<<) can be used to quickly perform the power-of-two. In general, a mask with the Nth bit set can be computed as

(1 << n)

Thus to check the Nth bit from a variable v, we can perform the operation

bool nth_is_set = (v & (1 << n)) != 0

Changing bits in flag words

Writing, reading or toggling bits in flags can be done only using the OR, AND and NOT operations - operations which can be performed quickly in the processor.

To set a bit, OR the status byte with a mask byte. Any bits set in the mask byte or the status byte will be set in the result.

int setBit(int val, int bit_position)
{
  return val | (1 << bit_position);
}

To clear a bit, perform a NOT operation on the mask byte, then AND it with the status byte. The result will have the appropriate flag cleared (set to 0).

int clearBit(int val, int bit_position)
{
  return val & ~(1 << bit_position);
}

To toggle a bit, XOR the status byte and the mask byte. This will set a bit if it is cleared or clear a bit if it is set.

int toggleBit(int val, int bit_position)
{
  return val ^ (1 << bit_position);
}

See also